import { Mesh } from '@babylonjs/core/Meshes/mesh';
import { DefaultStage } from '../default-stage';
import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder';
import { RawAssetsUrl } from '../../raw-asset-info';
import { Quaternion } from '@babylonjs/core/Maths/math.vector';
import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial';
import { AnimationFrame, Texture } from 'babylon-lib/index';


class Sea {

    private static animateReq = {};

    private static _stage: DefaultStage;
    private static _mesh: Mesh;

    public static initialize(stage: DefaultStage) {
        this._stage = stage;
        this._mesh = this.initializeMesh();
        this.animate(true);
    }

    public static animate(play: boolean): void {
        if (!play) {
            AnimationFrame.cancel(this.animateReq);
            return;
        }
        if (AnimationFrame.isRunning(this.animateReq)) return;
        const material = this._mesh.material as StandardMaterial;
        const texture = material.emissiveTexture as Texture;
        AnimationFrame.request(() => {
            texture.uOffset -= 0.0001;
        }, 16, 200, this.animateReq);
    }

    private static initializeMesh(): Mesh {
        const plane = MeshBuilder.CreatePlane('SeaMesh', { size: 200 }, this._stage.mainScene);
        plane.rotationQuaternion = Quaternion.FromEulerAngles(Math.PI * 0.5, 0, 0);
        plane.position.set(0, -0.2, 0);
        plane.isPickable = false;

        const texture = this._stage.loader(this._stage.mainScene).getTextureTaskInfo(RawAssetsUrl.textureWater)?.texture!;
        texture.uScale = 2;
        texture.vScale = 2;
        const material = new StandardMaterial('seaMaterial', this._stage.mainScene);
        material.disableLighting = true;
        material.emissiveTexture = texture;

        plane.material = material;
        plane.isPickable = false;
        return plane;
    }

}


export { Sea };